Let's learn how to execute our lambda function locally (to avoid deploying every time we want to test it).
We'll be using the AWS Serverless Application Model (SAM) for that.
Check if you have SAM already installed by running:
- sam --help.
👍 I don't, so I followed the instructions for installing it (on mac OS).
We'll need docker, homebrew and the SAM CLI (brew tap aws/tap and brew install aws-sam-cli).
Then, we need to generate a cloudformattion template by running:
- cdk synth --no-staging > template.yaml
Open template.yaml and take a moment to appreciate all the code that you didn't need to write (since it's auto-generated by cloudformattion).
Copy your lambda function's id, which can be found in several places throughout the .yaml file. Mine looks like this: HelloLambda3D9C82D6.
Back in your terminal, invoke the function by running:
- sam local invoke HelloLambda3D9C82D6
(of course, replace this with your lambda id).
👍 Make sure you have docker running too!
We won't be able to pass in an event with our existing code, and so event.path will result in undefined. We can pass it our own events instead!
In your project root directory create a directory called sample_events, inside, create a file called hello.json with the following contents:
{"path": "/hello/nothanii","body": "hello"}
Then run:
- sam local invoke HelloLambda3D9C82D6 --event=sample_events/hello.json
You should get the following output:
{"statusCode": 200,"headers": {"Content-Type":"text/plain"},"body":"Hello, nothanii friends! You've hit /hello/nothanii\n"}